package com.couchcrowler.server.parser;

import java.util.HashSet;

import org.apache.commons.lang.StringUtils;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.couchcrowler.shared.Location;
import com.couchcrowler.shared.Profile;

public class ProfileHandler extends DefaultHandler {

	private Profile profile;

	private StringBuffer text = new StringBuffer();

	public ProfileHandler() {
		profile = new Profile();
		profile.setLocation(new Location());
		profile.setContactsIds(new HashSet<String>());
	}

	public Profile getProfile() {
		return profile;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
	 */
	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		text.append(ch, start, length);
	}

	private boolean readingContacts = false;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
	 * java.lang.String, java.lang.String, org.xml.sax.Attributes)
	 */
	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		if (localName.equalsIgnoreCase("contacts")) {
			readingContacts = true;
		}

		text.setLength(0);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String,
	 * java.lang.String, java.lang.String)
	 */
	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if (localName.equalsIgnoreCase("id")) {
			String id = getText();
			if (readingContacts) {
				if (id != null) {
					profile.getContactsIds().add(id);
				}
			} else {
				profile.setId(id);
			}
		} else if (localName.equalsIgnoreCase("name")) {
			profile.setName(getText());
		} else if (localName.equalsIgnoreCase("latitude")) {
			profile.getLocation().setLatitude(getDouble());
		} else if (localName.equalsIgnoreCase("longitude")) {
			profile.getLocation().setLongitude(getDouble());
		} else if (localName.equals("picture")) {
			profile.setPictureUrl(getText());
		} else if (localName.equalsIgnoreCase("contacts")) {
			readingContacts = false;
		}
	}

	private String getText() {
		try {
			return StringUtils.defaultIfEmpty(text.toString(), null);
		} finally {
			text.setLength(0);
		}
	}

	private double getDouble() {
		double result = 0;
		try {
			String text = getText();
			if (text != null) {
				result = Double.valueOf(text);
			}
		} catch (NumberFormatException numberFormatException) {
			// ignore
		}
		
		return result;
	}
}